import network
import time
from Light import Lighter


class WiFi:
    def __init__(self):
        self.wlan = network.WLAN(network.STA_IF)
        self.wlan.active(True)
        self.wifi_list = []

    def connect(self, ssid, pwd):
        self.wlan.disconnect()
        self.wlan.connect(ssid, pwd)

        for _ in range(10):
            if self.wlan.isconnected():
                return True
            else:
                time.sleep(0.5)
        return False

    def exist(self, ssid):
        self.wifi_list = self.wlan.scan()
        return ssid in [item[0].decode() for item in self.wifi_list]

    def ifconfig(self):
        # IP地址、子网掩码、网关和DNS服务器的元组
        # return: (ip, mask, gateway, dns)
        return self.wlan.ifconfig()

    def is_connected(self):
        return self.wlan.isconnected()

if __name__ == '__main__':
    wifi_ssid = ""
    wifi_pwd = ""

    wifi = WiFi()
    lighter = Lighter()

    lighter.blink(0.3)
    print("searching...")
    while not wifi.exist(wifi_ssid):
        time.sleep(1)
        print(f"WIFI:[{wifi_ssid}]not found")

    print("connecting...")
    lighter.blink(1)
    wifi.connect(wifi_ssid, wifi_pwd)

    print("connected")
    lighter.on()

